package br.com.sig.security.presentation.action;

import java.util.ArrayList;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import br.com.sig.business.exception.BaseException;
import br.com.sig.cadastro.pessoas.business.model.entity.PessoaFisica;
import br.com.sig.cadastro.recursoshumanos.business.model.entity.Cargo;
import br.com.sig.cadastro.recursoshumanos.business.model.entity.Departamento;
import br.com.sig.cadastro.recursoshumanos.business.model.entity.Funcionario;
import br.com.sig.presentation.action.BaseAction;
import br.com.sig.presentation.action.ModalAction;
import br.com.sig.security.business.model.bo.UserBO;
import br.com.sig.security.business.model.entity.Role;
import br.com.sig.security.business.model.entity.User;
import br.com.sig.security.business.service.UserService;

@Named
@ViewScoped
public class UserAction extends BaseAction<User> {

	private static final long serialVersionUID = -1634914936667632291L;
	
	private ModalAction<Role> roleModal = null;

	@Inject
	private UserBO userBO;
	
	@Inject
	private UserService userService;

	@PostConstruct
	public void init() {
		setService(userBO);
	}
	
	@Override
	protected User createInstance() {
		User user = super.createInstance();
		user.setFuncionario(new Funcionario());
		user.getFuncionario().setPessoaFisica(new PessoaFisica());
		user.getFuncionario().setCargo(new Cargo());
		user.getFuncionario().setDepartamento(new Departamento());
		user.setRoles(new ArrayList<Role>());
		return user;
	}
	
	@Override
	public void persist() {
		try {
			userService.persist(getInstance());
			afterPersist();
		} catch (BaseException e) {
			messages.error(e.getMessage());			
		}		
	}
	
	public ModalAction<Role> getRoleModal() {
		if (this.roleModal == null) {
			this.roleModal = new ModalAction<Role>(getInstance().getRoles());
		}
		return this.roleModal;
	}
}